package com.czl.module_service.viewmodel

import android.text.TextUtils
import android.util.Log
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.AreaIdBean
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.tengyun.*
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.DateHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_service.adapter.PurchaseApplyAddAdapter
import com.czl.module_service.adapter.asset.BorrowSortChoosedAdapter

class PurchaseApplyAddViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    val uc = UiChangeEvent()
    var isFirst : Boolean = false
    var list : MutableList<PurchaseOrderBean> = arrayListOf()
    var entityBean = PurchaseBean()
    var purchaseOrderBean = PurchaseOrderBean()
    var applicaitonName = ObservableField("")
    var purchaseTypeName = ObservableField("请选择采购类型")
    var assetTypeName = ObservableField("请选择资产类型")
    var companyName = ObservableField(model.getLocalUserInfo()?.companyName)
    var projectName = ObservableField(model.getAreaName())
    var applyComment = ObservableField("")
    var projectList : List<AreaIdBean> = model.getAreaList()
    var isLowasset : Int = 0      // 判断是否为低值易耗
    var totalCount = ObservableField("0")
    var totalPrice = ObservableField("0.00元")
    var adapter : PurchaseApplyAddAdapter? = null
    var fileParamUrl = ObservableField("")
    var fileParamList : MutableList<FileBean> = arrayListOf()
    var businessType = 1
    var projectId: Int? = null

    class UiChangeEvent {
        val choiceImgEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val roleCompleteEvent: SingleLiveEvent<List<Any?>> = SingleLiveEvent()
        val loadCompleteEvent: SingleLiveEvent<MutableList<PurchaseOrderBean>> = SingleLiveEvent()
        val choiceFacilityTypeEvent: SingleLiveEvent<Any> = SingleLiveEvent()
        val choiceOwnerCompanyEvent: SingleLiveEvent<Any> = SingleLiveEvent()
        val choiceOwnerCompanyListEvent: SingleLiveEvent<ListBean<CompanyBean>> = SingleLiveEvent()
        val choiceOwnerProjectEvent: SingleLiveEvent<Any> = SingleLiveEvent()
        val clearFacilityListEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val choiceAdapterFileEvent: SingleLiveEvent<ImgRspBean> = SingleLiveEvent()
        val allSortBeanCompleteEvent: SingleLiveEvent<ListBean<SortBean>> = SingleLiveEvent()
    }

    val onImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(MODEL_IMG)
    })

    val onSubmitClickCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        addPurchaseApplication()
    })

    val addSortLayout: BindingCommand<Any> = BindingCommand(BindingAction {
        isFirst = true
        getSortList()
    })

    val choosePurchaseOrder: BindingCommand<Any> = BindingCommand(BindingAction {
        startContainerActivity(AppConstants.Router.Service.F_SERVICE_PURCHASE_ORDER_CHOOSE)
    })

    val getFacilityTpyeInfo: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceFacilityTypeEvent.postValue(0)
    })
    val getOwerCompanyInfo: BindingCommand<Any> = BindingCommand(BindingAction {
//        uc.choiceOwnerCompanyEvent.postValue(0)
    })
    val getOwerProjectInfo: BindingCommand<Any> = BindingCommand(BindingAction {
//        uc.choiceOwnerProjectEvent.postValue(0)
    })

    fun initData() {
        entityBean.parentCompanyId = model.getLoginCompanyId()?.toInt()
        entityBean.projectId = model.getAreaId().toInt()
    }

    fun getSortList() {
        val list : MutableList<PurchaseOrderBean> = arrayListOf()
        list.add(PurchaseOrderBean())
        uc.loadCompleteEvent.postValue(list)
    }

    fun getCompanyList(
        userId: String? = model.getLocalUserInfo()?.userId
    ) {
        model.mTengYunHttpDataSource.selectCompanyByModule(
            GsonUtils.toJson(
                mapOf(
                    "userId" to userId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<CompanyBean>>>() {
                override fun onResult(t: BaseBean<ListBean<CompanyBean>>) {
                    if (t.state == 0) {
                        uc.choiceOwnerCompanyListEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun getIdByNeighNo() {
        model.mTengYunHttpDataSource.getIdByNeighNo(
            GsonUtils.toJson(
                mapOf(
                    "neighNo" to model.getAreaId()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<Int>>() {
                override fun onResult(t: BaseBean<Int>) {
                    if (t.state == 0) {
                        projectId = t.data
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun getRoleProcessList() {
        model.mTengYunHttpDataSource.getRoleProcessList(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "businessId" to 0
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<List<Any?>>>() {
                override fun onResult(t: BaseBean<List<Any?>>) {
                    if (t.state == 0) {
                        uc.roleCompleteEvent.postValue(t.data)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    // 新增采购申请
    private fun addPurchaseApplication() {
        val data = adapter?.data
        list = adapter?.data!!
        Log.e("viewModel", "data:" +data?.size)
        if (applicaitonName.get().isNullOrEmpty()) {
            showNormalToast("请填写采购名称")
            return
        }
        /*if (applyComment.get().isNullOrEmpty()) {
            showNormalToast("请填写采购说明")
            return
        }*/
        val filterList = list.filter { it.assetType != null || it.purchaseName != null || it.model != null || it.unit != null || it.purchaseCount != null || it.price != null }
        for (bean in filterList) {
            if (bean.assetType == null) {
                showNormalToast("请选择资产类型")
                return
            }
            if (bean.purchaseName == null) {
                showNormalToast("请输入采购内容")
                return
            }
            if (bean.model == null) {
                showNormalToast("请输入型号")
                return
            }
            if (bean.purchaseCount == null || bean.purchaseCount!!.toInt() <= 0) {
                showNormalToast("请输入数量,且数量大于0")
                return
            }
            if (bean.price == null || bean.price!!.toDouble() <= 0) {
                showNormalToast("请输入价格，且价格高于0")
                return
            }
        }
        val list : MutableList<PurchaseOrderBean> = arrayListOf()
        filterList.forEach {
            val price = it.price?.toDouble()
            val count = it.purchaseCount?.toInt()
            if (price != null) {
                it.planPurchaseFee = (price * count!!).toString()
            } else {
                it.planPurchaseFee = "0.00"
            }
            list.add(it)
        }
        model.mTengYunHttpDataSource.addApplication(
            GsonUtils.toJson(
                mapOf(
                    "applicationUserId" to model.getLocalUserInfo()?.userId,
                    "projectId" to projectId,
                    "createCompanyId" to model.getLoginCompanyId()?.toInt(),
                    "parentCompanyId" to model.getLoginCompanyId()?.toInt(),
                    "applicaitonName" to applicaitonName.get(),
                    "note" to applyComment.get(),
                    "isLowasset" to 0,
                    "applicationProjectList" to list,
                    "applicaitonTime" to DateHelper.getNow(),
                    "fileParam" to fileParamList,
                    "type" to businessType,
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("新增成功")
                        uc.clearFacilityListEvent.postValue(0)
                        LiveBusCenter.postGoToTabEvent(1)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    companion object {
        const val MODEL_IMG = 100
        const val ADAPTER_IMG = 101
    }

    fun uploadHeadImg(imgSrc: String, type: Int) {
        model.apply {
            uploadHeadImg("szchd", imgSrc, "assets")
                .compose(RxThreadHelper.rxSchedulerHelper(this@PurchaseApplyAddViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            if (type == MODEL_IMG) {
                                fileParamUrl.set(t.data?.url)
                                val bean : ImgRspBean = t.data!!
                                val fileBean = FileBean()
                                fileBean.url = bean.url
                                fileBean.fileUrl = bean.url
                                fileBean.name = bean.name
                                fileBean.fileName = bean.name
                                var list : MutableList<FileBean> = arrayListOf()
                                list.add(fileBean)
                                fileParamList = list
                            } else if (type == ADAPTER_IMG) {
                                uc.choiceAdapterFileEvent.postValue(t.data)
                            }
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }

    fun getSortAllList() {
        model.mTengYunHttpDataSource.getSortAllList(
            GsonUtils.toJson(
                mapOf(
                    "companyId" to model.getLoginCompanyId()?.toInt(),
                    "propCompanyId" to model.getLoginCompanyId()?.toInt()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<SortBean>>>() {
                override fun onResult(t: BaseBean<ListBean<SortBean>>) {
                    if (t.state == 0) {
                        uc.allSortBeanCompleteEvent.postValue(t.data)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }
}